/*************************************************************************
	> File Name: transport_manager.c
    > Author: xuwenlong
    > Mail: myxuan475@126.com
	> Created Time: 2018年01月16日 星期二 18时05分33秒
 ************************************************************************/

#include <stdio.h>
#include "transport_manager.h"
#include <utils/config.h>

TransportManager::TransportManager(int index)
    :m_pRemoteTask(NULL),
      m_iIndex(index),
      m_pLocalTask(NULL)
#ifdef HTTP_SERVER
    ,m_pServer(NULL)
#endif
{
#ifdef HTTP_SERVER
    if (index == 0) {
        m_pServer = new Server();
        m_pServer->StartServer(ACQ_PORT);
    }
#endif
}

TransportManager::~TransportManager()
{
    if (m_pRemoteTask) {
        delete m_pRemoteTask;
    }

    if (m_pLocalTask) {
        delete m_pLocalTask;
    }
#ifdef HTTP_SERVER
    if (m_pServer)
        delete m_pServer;
#endif
}

void TransportManager::SetupRemoteTask()
{
    if (!m_pRemoteTask){
        m_pRemoteTask = new RemoteTask(this);
    }
    if (m_pRemoteTask && m_pRemoteTask->IsTaskExit()){
        m_pRemoteTask->StartTask();
    }
}

void TransportManager::SetupLocalTask()
{
    if (!m_pLocalTask && m_iIndex == 0)
        m_pLocalTask = new LocalTask();
}

void TransportManager::ExitTask()
{
    if (m_iIndex == 0)
        m_pLocalTask->ExitTask();
    m_pRemoteTask->ExitTask();
#ifdef HTTP_SERVER
    if (m_pServer && m_iIndex == 0)
        m_pServer->StopServer();
#endif
}

void TransportManager::RegisterModules(ModuleInterface *module)
{
    /* remote */
    m_pRemoteTask->RegisterInterface(module,1);

    /* local */
//    m_pLocalTask->RegisterInterface(module);
    if (m_iIndex == 0)
        module->RegisterModule((DevTransportInterface*)m_pLocalTask);
}

void* TransportManager::GetTask(DAS_TASK task)
{
    return ::GetTask(task,m_iIndex);
}

int TransportManager::GetIndex()
{
    return m_iIndex;
}

const string TransportManager::GetSection()
{
    if (m_iIndex == 0 &&
            utils::HasSection("Config.ini","GATEWAY")) {
        return "GATEWAY";
    }
    else {
        char center[10];
        sprintf(center,"CENTER%d",m_iIndex+1);
        return center;
    }
}


